<template>
  <div class="staff-box">
    <!-- height: 560px; -->
    <a-card :bordered="false" style="height: 750px;width: 100%;">
      <div class="table-page-search-wrapper" style="margin-bottom: 10px;">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="指标名称">
                <a-input v-model="pagination.name" placeholder="请输入指标名称"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="指标编码">
                <a-input v-model="pagination.code" placeholder="请输入指标编码"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="描述">
                <a-input v-model="pagination.description" placeholder="请输入描述信息"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="值类型">
                <a-select placeholder="请选择值类型" v-model="pagination.valueType">
                  <a-select-option :value="item.id" v-for="(item, index) in valueTypeList" :key="index">{{
                    item.name
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="收支类型">
                <a-select placeholder="请选择收支类型" v-model="pagination.inOrOut">
                  <a-select-option :value="item.id" v-for="(item, index) in TypeList" :key="index">{{
                    item.name
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-button type="primary" @click="onSearch">查询</a-button>
              <a-button style="margin-left: 8px" @click="onReset">重置</a-button>
            </a-col>
            <!-- <a-col :md="!advanced && 8 || 24" :sm="24">
                                <span class="table-page-search-submitButtons"
                                    :style="advanced && { float: 'right', overflow: 'hidden' } || {}">
                                    <a-button type="primary" @click="onSearch">查询</a-button>
                                    <a-button style="margin-left: 8px" @click="onReset">重置</a-button>
                                    <a @click="toggleAdvanced" style="margin-left: 8px">
                                        {{ advanced ? '收起' : '展开' }}
                                        <a-icon :type="advanced ? 'up' : 'down'" />
                                    </a>
                                </span>
                            </a-col> -->
          </a-row>
        </a-form>
      </div>
      <a-row :gutter="8">
        <div class="tree-container">
          <div class="left">
            <div class="filter-container">
              <a-button type="primary" @click="cateAdd(1)" icon="plus">
                新增指标类别
              </a-button>
            </div>
            <a-col :span="6">
              <div class="overflow-tree">
                <a-spin :spinning="treeOnLoad" style="width: 280px;">
                  <div class="tree-box">
                    <a-button type="primary" size="small" @click="allTable">全部</a-button>
                    <a-tree
                      v-if="!treeOnLoad"
                      :tree-data="treeData"
                      draggable
                      blockNode
                      v-model="selectedKeys"
                      :defaultExpandAll="true"
                      :replaceFields="replaceFields"
                      :autoExpandParent="true"
                      :defaultExpandedKeys="selectedKeys"
                      @select="onSelect"
                      :defaultSelectedKeys="selectedKeys"
                      :selectedKeys="selectedKeys"
                      class="aTree"
                      @drop="onDrop">
                      <template v-slot:title="nodeData">
                        <div
                          @mouseenter="mouseenterDict(nodeData)"
                          @mouseleave="mouseleaveDict(nodeData)"
                          class="treeItem">
                          <div
                            style="width: 130px;overflow: hidden; text-overflow: ellipsis; white-space: nowrap;-webkit-line-clamp:1;">
                            {{ nodeData.categoryName }}</div>
                          <a-button-group
                            v-show="mouseenterId == nodeData.categoryId"
                            class="treeGroup">
                            <a-button
                              size="small"
                              @click="cateAdd(nodeData)"
                              icon="plus-circle"
                              title="添加"></a-button>
                            <a-button
                              size="small"
                              @click="cateEdit(nodeData)"
                              icon="form"
                              title="修改"></a-button>
                            <a-button
                              size="small"
                              icon="close-circle"
                              title="删除"
                              @click="cateDelete(nodeData)"></a-button>
                          </a-button-group>
                        </div>
                      </template>
                    </a-tree>
                  </div>

                </a-spin>
              </div>

            </a-col>
          </div>
          <div class="right">
            <a-col :span="18" style="width: 97%;">
              <div class="worker">
                <a-button type="primary" icon="plus" @click="onAdd" style="margin-right: 10px;">
                  新增指标
                </a-button>
                <a-button type="primary" @click="onFill()">
                  填报
                </a-button>
              </div>
              <a-table
                :columns="columns"
                :data-source="dataSource"
                bordered
                :loading="loading"
                :rowKey="(record) => { return record.indicatorId }"
                :scroll="{ x: true, y: 10000 }"
                :pagination="pagination">
                <template slot="valueType" slot-scope="text,record">
                  <span>
                    {{ record.valueType == 1 ? '金额' :
                      record.valueType == 2 ? '数值' :
                      record.valueType == 3 ? '百分比' : '计数' }}
                  </span>
                </template>
                <template slot="inOrOut" slot-scope="text,record">
                  <span>
                    {{ record.inOrOut == 1 ? '收入' :
                      record.inOrOut == 2 ? '支出' : '其它' }}
                  </span>
                </template>
                <span slot="action" slot-scope="text, record">
                  <div>
                    <a href="javascript:;" @click="onEdit(record)">编辑</a>
                    <a-divider type="vertical" />
                    <a href="javascript:;" @click="onDel(record)">删除</a>
                  </div>
                </span>
              </a-table>
            </a-col>
          </div>
        </div>
      </a-row>
      <saveModal ref="saveModal" @success="apiAll" @close="dialog.save = false">
      </saveModal>
      <cateSaveModal ref="cateSaveModal" v-if="dialog.cateSave" @success="apiAll" @close="dialog.cateSave = false">
      </cateSaveModal>
      <fillDataModal ref="fillDataModal">

      </fillDataModal>
    </a-card>
  </div>
</template>

<script>

import { getCateIndicator, deleteCateIndicator, getIndicators, deleteIndicators, editCateIndicator } from '@/api/budget'

import saveModal from './save'
import cateSaveModal from './cateSave'
import fillDataModal from './fillData'
// 弹窗提示  用于删除
import { Modal } from 'ant-design-vue'
export default {
    components: {
        cateSaveModal,
        saveModal,
        fillDataModal
    },
    data () {
        return {
            // 单位
            replaceFields: {
                children: 'children',
                title: 'categoryName',
                key: 'categoryId',
                value: 'categoryId'
            },
            // 树状图加载
            treeOnLoad: true,
            treeData: [],
            // 权限树是否显示操作图标
            mouseenterId: '',
            selectedKeys: [],

            // 组件的删除与创建
            dialog: {
                cateSave: false,
                save: false
            },
            columns: [
                {
                    title: '名称',
                    dataIndex: 'name',
                    key: 'name',
                    align: 'center',
                    width: 270
                },
                {
                    title: '指标编码',
                    dataIndex: 'code',
                    key: 'code',
                    align: 'center',
                    width: 120
                },
                {
                    title: '指标类别',
                    dataIndex: 'categoryName',
                    key: 'categoryName',
                    align: 'center',
                    width: 180
                },
                {
                    title: '值类型',
                    dataIndex: 'valueType',
                    key: 'valueType',
                    width: 100,
                    align: 'center',
                    scopedSlots: { customRender: 'valueType' }
                },
                {
                    title: '收支类型',
                    dataIndex: 'inOrOut',
                    key: 'inOrOut',
                    width: 100,
                    align: 'center',
                    scopedSlots: { customRender: 'inOrOut' }
                },
                {
                    title: '贡献比重',
                    dataIndex: 'proportion',
                    key: 'proportion',
                    width: 100,
                    align: 'center'
                },
                {
                    title: '操作',
                    dataIndex: 'action',
                    align: 'center',
                    fixed: 'right',
                    width: 150,
                    scopedSlots: { customRender: 'action' }
                }
            ],
            dataSource: [],
            // 类别id
            cateId: '',
            // 表格是否加载
            loading: false,
            pagination: {
                // 分页配置
                pageSize: 6, // 每页显示的条数
                showQuickJumper: true, // 是否可以快速跳转到指定页
                showTotal: total => `共 ${total} 条`, // 显示总条数和当前数据范围
                current: 1, // 当前页数
                total: 10, // 总条数
                categoryId: '',
                name: '',
                code: '',
                // 下拉数据数据为空，则没有提示所有要赋值为undefined
                inOrOut: undefined,
                valueType: undefined,
                description: '',
                onChange: this.handlePageChange // 页码改变时的回调函数
            },

            // 搜索
            valueTypeList: [{ id: 1, name: '金额' },
            { id: 2, name: '数值' },
            { id: 3, name: '百分比' },
            { id: 4, name: '计数' }],
            TypeList: [{ id: 1, name: '收入' }, { id: 2, name: '支出' }, { id: 3, name: '其它' }],
            // 高级搜索 展开/关闭
            advanced: false
        }
    },
    created () {
        this.apiAll()
    },
    methods: {
        editDrop (dragObj) {
            editCateIndicator(dragObj).then(res => {
                if (res.code == 200) {
                    this.$notification['success']({
                        message: '提示',
                        description: '拖拽成功！',
                        duration: 8
                    })
                } else {
                    this.$notification['error']({
                        message: '提示',
                        description: res.message,
                        duration: 8
                    })
                }
            })
        },
        // 拖动完成触发
        onDrop (info) {
            const dropKey = info.node.eventKey // 目标节点id
            const dragKey = info.dragNode.eventKey // 拖拽节点id
            const dropPos = info.node.pos.split('-') // 层级

            const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1])
            const treeId = this.treeData[0].categoryId
            if (dropKey == treeId && [-1, 1].includes(dropPosition)) {
                // 拖拽节点上级为-1，拖拽节点下面为1，正中间为0
                // console.log({ info: info, '目标节点': dropKey, '拖拽节点': dragKey, '？？层级': dropPos, '层级': dropPosition })
                // let { event, node, dragNode, dragNodesKeys } = info
                // console.log('实际应用中可获取如下对象属性', {
                //     event,
                //     '移入的节点': node,
                //     '移动的节点': dragNode,
                //     '当前展开的节点': dragNodesKeys,
                // })
                return false
            }
            const loop = (data, key, callback) => {
                data.forEach((item, index, arr) => {
                    if (item.categoryId === key) {
                        return callback(item, index, arr)
                    }
                    if (item.children) {
                        return loop(item.children, key, callback)
                    }
                })
            }
            const data = [...this.treeData]
            // Find dragObject
            let dragObj
            loop(data, dragKey, (item, index, arr) => {
                arr.splice(index, 1)
                dragObj = item
            })
            if (!info.dropToGap) {
                // Drop on the content
                loop(data, dropKey, (item) => {
                    item.children = item.children || []
                    // where to insert 示例添加到尾部，可以是随意位置
                    dragObj.parentCategoryId = item.categoryId
                    item.children.push(dragObj)
                })
            } else if (
                (info.node.children || []).length > 0 && // Has children
                info.node.expanded && // Is expanded
                dropPosition === 1 // On the bottom gap
            ) {
                loop(data, dropKey, (item) => {
                    item.children = item.children || []
                    // where to insert 示例添加到尾部，可以是随意位置
                    dragObj.parentCategoryId = item.categoryId
                    item.children.unshift(dragObj)
                })
            } else {
                let ar
                let i
                loop(data, dropKey, (item, index, arr) => {
                    ar = arr
                    i = index
                })

                if (dropPosition === -1) {
                    ar.splice(i, 0, dragObj)
                } else {
                    ar.splice(i + 1, 0, dragObj)
                }
            }
            this.editDrop(dragObj)
            this.treeData = data
        },
        // 填报
        onFill () {
            this.$nextTick(() => {
                this.$refs.fillDataModal.open()
            })
        },
        // 高级搜索切换
        toggleAdvanced () {
            this.advanced = !this.advanced
        },
        // 搜索
        onSearch () {
            this.pagination.current = 1
            this.pagination.pageSize = 6
            this.tableData()
        },
        // 重置
        onReset () {
            this.pagination = {
                // 分页配置
                pageSize: 6, // 每页显示的条数
                showTotal: total => `共 ${total} 条`, // 显示总条数和当前数据范围
                current: 1, // 当前页数
                total: 10, // 总条数
                categoryId: '',
                name: '',
                code: '',
                inOrOut: undefined,
                valueType: undefined,
                description: ''
            }
            this.tableData()
        },
        apiAll () {
            this.GetTree()
            this.dialog = {
                cateSave: false
            }
        },
        // 左侧鼠标悬浮展示图标
        mouseenterDict (data) {
            this.mouseenterId = data.categoryId
        },
        // 左侧鼠标离开不展示图标
        mouseleaveDict () {
            this.mouseenterId = ''
        },
        handlePageChange (page, pageSize) {
            this.pagination.current = page
            this.tableData()
        },
        // 项目类别树
        GetTree () {
            const _this = this
            getCateIndicator().then(res => {
                if (res.code == 200) {
                    this.treeData = res.data
                    this.treeOnLoad = false
                    this.dialog.save = false
                }
            })
            this.tableData()
        },
        // 节点点击
        onSelect (keys, e) {
            if (keys.length == 0) return
            this.cateId = Number(keys.join(''))
            this.selectedKeys = keys
            this.pagination.categoryId = this.cateId
            this.tableData()
        },
        allTable () {
            this.cateId = ''
            this.selectedKeys = []
            this.pagination = {
                // 分页配置
                pageSize: 6, // 每页显示的条数
                current: 1, // 当前页数
                total: 10, // 总条数
                categoryId: '',
                name: '',
                code: '',
                inOrOut: undefined,
                valueType: undefined,
                description: ''
            }
            const par = {
                ...this.pagination
            }
            // 接口参数不能为undefined，需要赋值为空
            const { inOrOut, valueType } = par
            par.inOrOut = (inOrOut == undefined ? '' : inOrOut)
            par.valueType = (valueType == undefined ? '' : valueType)
            this.loading = true
            getIndicators(par).then(res => {
                if (res.code == 200) {
                    this.dataSource = res.data.datas
                    this.loading = false
                }
            })
        },
        // 获取员工
        tableData () {
            const par = {
                ...this.pagination
            }
            // 接口参数不能为undefined，需要赋值为空
            const { inOrOut, valueType } = par
            par.inOrOut = (inOrOut == undefined ? '' : inOrOut)
            par.valueType = (valueType == undefined ? '' : valueType)
            this.loading = true
            getIndicators(par).then(res => {
                if (res.code == 200) {
                    this.dataSource = res.data.datas
                    this.loading = false
                }
            })
        },
        // 添加指标
        onAdd () {
            this.dialog.save = true
            const par = {
                categoryId: this.cateId
            }
            const _this = this
            _this.$nextTick(() => {
                _this.$refs.saveModal.open('add').setData(par)
            })
        },
        // 编辑指标
        onEdit (nodeData) {
            this.dialog.save = true
            // let par = {
            //     ...nodeData,
            //     organizationUnitId: this.orgId
            // }
            this.$nextTick(() => {
                this.$refs.saveModal.open('edit').setData(nodeData)
            })
        },
        // 删除指标
        onDel (nodeData) {
            const _this = this
            Modal.confirm({
                title: '删除信息',
                content: '确定要删除吗？',
                onOk: () => {
                    deleteIndicators(nodeData.indicatorId).then(res => {
                        if (res.code == 200) {
                            _this.GetTree()
                            _this.$message.success('删除成功')
                        } else {
                            _this.$message.error(res.message)
                        }
                    })
                }
            })
        },

        // 新增项目类别
        cateAdd (nodeData) {
            this.dialog.cateSave = true
            this.$nextTick(() => {
                this.$refs.cateSaveModal.open('add').setData(nodeData)
            })
        },
        // 编辑项目类别
        cateEdit (nodeData) {
            this.dialog.cateSave = true
            this.$nextTick(() => {
                this.$refs.cateSaveModal.open('edit').setData(nodeData)
            })
        },
        // 删除项目类别
        cateDelete (nodeData) {
            const _this = this
            Modal.confirm({
                title: '删除信息',
                content: '确定要删除吗？',
                onOk: () => {
                    deleteCateIndicator(nodeData.categoryId).then(res => {
                        if (res.code == 200) {
                            _this.GetTree()
                            _this.$message.success('删除成功')
                        } else {
                            _this.$message.error(res.message)
                        }
                    })
                }
            })
        }

    }
}
</script>

<style lang="less" scoped>
.tree-box {
    margin-top: 20px;
}

.overflow-tree {
    // overflow-y: scroll;
    // overflow-x: hidden;
    // height: 420px;
    // width: 280px;
}

.aTree {
    overflow-y: scroll;
    overflow-x: hidden;
    height: 500px;
    width: 280px;
}

.staff-box {
    width: 100%;
    background-color: #fff;
    overflow-y: hidden;
    overflow-x: auto;
    white-space: nowrap;
    border-radius: 2px;
}

.tree-container {
    display: flex;
    flex-direction: row;

    .right {
        width: 900px;
        display: flex;
    }
}

.filter-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.worker {
    padding-bottom: 10px;
}

.treeItem {
    display: flex;
    justify-content: space-between;
}

.treeGroup {
    margin-top: -2px;
    margin-right: -6px;
}
</style>
